//
//  DMFacebookAdCountManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/21.
//  Facebook广告计数管理工具类 - 统一管理Facebook广告的展示和点击计数逻辑
//

#import "DMFacebookAdCountManager.h"
#import "IMSDKStartupConfigManager.h"
#import "IMLogUtils.h"

@interface DMFacebookAdCountManager ()

@property (nonatomic, strong) dispatch_queue_t facebookCountQueue;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *showCountCache;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *clickCountCache;

@end

@implementation DMFacebookAdCountManager

#pragma mark - 单例模式

+ (instancetype)sharedManager {
    static DMFacebookAdCountManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 创建串行队列确保线程安全
        self.facebookCountQueue = dispatch_queue_create("com.dualmediationsdk.facebook.count", DISPATCH_QUEUE_SERIAL);
        
        // 初始化缓存字典
        self.showCountCache = [[NSMutableDictionary alloc] init];
        self.clickCountCache = [[NSMutableDictionary alloc] init];
        
        [IMLogUtils info:IMLogTagAd format:@"📊 [Facebook Count Manager] 初始化完成"];
    }
    return self;
}

#pragma mark - 公共接口

- (void)handleFacebookAdControlWithAdNetwork:(NSString *)adNetwork 
                                   eventType:(NSString *)eventType 
                                 managerType:(NSString *)managerType {
    // 检查是否为Facebook广告网络
    if (![self isFacebookAdNetwork:adNetwork]) {
        return;
    }
    
    // 获取Facebook控制配置
    NSString *fbControlConfig = [[IMSDKStartupConfigManager sharedManager] getFacebookControlConfiguration];
    if (!fbControlConfig || fbControlConfig.length == 0) {
        [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] Facebook控制配置为空，跳过控制逻辑", managerType];
        return;
    }
    
    // 解析控制参数
    NSArray *params = [fbControlConfig componentsSeparatedByString:@";"];
    if (params.count < 3) {
        [IMLogUtils warning:IMLogTagAd format:@"📊 [%@] Facebook控制配置格式错误: %@", managerType, fbControlConfig];
        return;
    }
    
    NSInteger switchParam = [params[0] integerValue];
    NSInteger showCountThreshold = [params[1] integerValue];
    NSInteger clickRateThreshold = [params[2] integerValue];
    
    [IMLogUtils info:IMLogTagAd format:@"📊 [%@] Facebook控制参数 - 切换参数: %ld, 展示次数阈值: %ld, 点击率阈值: %ld", managerType, (long)switchParam, (long)showCountThreshold, (long)clickRateThreshold];
    
    // 只有当第一个参数为1时才执行控制逻辑
    if (switchParam != 1) {
        [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] Facebook控制开关关闭，跳过控制逻辑", managerType];
        return;
    }
    
    // 检查并重置按天计数
    [self checkAndResetDailyFacebookCountsForManager:managerType];
    
    // 更新计数器
    if ([eventType isEqualToString:@"display"]) {
        [self incrementFacebookShowCountForManager:managerType];
        [IMLogUtils info:IMLogTagAd format:@"📊 [%@] Facebook展示次数: %ld", managerType, (long)[self getFacebookShowCountForManager:managerType]];
    } else if ([eventType isEqualToString:@"click"]) {
        [self incrementFacebookClickCountForManager:managerType];
        [IMLogUtils info:IMLogTagAd format:@"📊 [%@] Facebook点击次数: %ld", managerType, (long)[self getFacebookClickCountForManager:managerType]];
    }
    
    // 检查是否达到控制条件
    NSInteger currentShowCount = [self getFacebookShowCountForManager:managerType];
    NSInteger currentClickCount = [self getFacebookClickCountForManager:managerType];
    
    if (currentShowCount >= showCountThreshold) {
        NSInteger clickRate = currentShowCount > 0 ? (currentClickCount * 100 / currentShowCount) : 0;
        [IMLogUtils info:IMLogTagAd format:@"📊 [%@] Facebook当前点击率: %ld%%", managerType, (long)clickRate];
        
        if (clickRate >= clickRateThreshold) {
            [IMLogUtils warning:IMLogTagAd format:@"📊 [%@] ⚠️ Facebook广告达到控制条件，展示次数: %ld, 点击率: %ld%%, 建议切换广告源", managerType, (long)currentShowCount, (long)clickRate];
            // 这里可以添加切换广告源的逻辑
        }
    }
}

- (BOOL)isFacebookAdNetwork:(NSString *)adNetwork {
    if (!adNetwork || adNetwork.length == 0) {
        return NO;
    }
    
    NSString *lowerAdNetwork = [adNetwork lowercaseString];
    return [lowerAdNetwork containsString:@"facebook"] ||
           [lowerAdNetwork containsString:@"meta"] ||
           [lowerAdNetwork containsString:@"fb"];
}

- (NSInteger)getFacebookShowCountForManager:(NSString *)managerType {
    __block NSInteger count = 0;
    dispatch_sync(self.facebookCountQueue, ^{
        NSString *key = [self showCountKeyForManager:managerType];
        count = [[NSUserDefaults standardUserDefaults] integerForKey:key];
    });
    return count;
}

- (NSInteger)getFacebookClickCountForManager:(NSString *)managerType {
    __block NSInteger count = 0;
    dispatch_sync(self.facebookCountQueue, ^{
        NSString *key = [self clickCountKeyForManager:managerType];
        count = [[NSUserDefaults standardUserDefaults] integerForKey:key];
    });
    return count;
}

- (void)checkAndResetDailyFacebookCountsForManager:(NSString *)managerType {
    dispatch_sync(self.facebookCountQueue, ^{
        NSString *todayString = [self getTodayDateString];
        NSString *dateKey = [self lastUpdateDateKeyForManager:managerType];
        NSString *lastUpdateDate = [[NSUserDefaults standardUserDefaults] stringForKey:dateKey];
        
        if (!lastUpdateDate || ![lastUpdateDate isEqualToString:todayString]) {
            // 新的一天，重置计数
            [IMLogUtils info:IMLogTagAd format:@"📊 [%@] 检测到新的一天，重置Facebook计数器", managerType];
            [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] 上次更新日期: %@, 今天日期: %@", managerType, lastUpdateDate ?: @"无", todayString];
            
            NSString *showCountKey = [self showCountKeyForManager:managerType];
            NSString *clickCountKey = [self clickCountKeyForManager:managerType];
            
            [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:showCountKey];
            [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:clickCountKey];
            [[NSUserDefaults standardUserDefaults] setObject:todayString forKey:dateKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            // 同步内存中的缓存
            [self.showCountCache setObject:@(0) forKey:managerType];
            [self.clickCountCache setObject:@(0) forKey:managerType];
            
            [IMLogUtils info:IMLogTagAd format:@"📊 [%@] Facebook计数器重置完成", managerType];
        } else {
            // 同一天，从本地存储加载计数
            NSString *showCountKey = [self showCountKeyForManager:managerType];
            NSString *clickCountKey = [self clickCountKeyForManager:managerType];
            
            NSInteger savedShowCount = [[NSUserDefaults standardUserDefaults] integerForKey:showCountKey];
            NSInteger savedClickCount = [[NSUserDefaults standardUserDefaults] integerForKey:clickCountKey];
            
            [self.showCountCache setObject:@(savedShowCount) forKey:managerType];
            [self.clickCountCache setObject:@(savedClickCount) forKey:managerType];
            
            [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] 加载今日Facebook计数 - 展示: %ld, 点击: %ld", managerType, (long)savedShowCount, (long)savedClickCount];
        }
    });
}

#pragma mark - 私有方法

- (void)incrementFacebookShowCountForManager:(NSString *)managerType {
    dispatch_async(self.facebookCountQueue, ^{
        NSString *key = [self showCountKeyForManager:managerType];
        NSInteger currentCount = [[NSUserDefaults standardUserDefaults] integerForKey:key];
        NSInteger newCount = currentCount + 1;
        
        [[NSUserDefaults standardUserDefaults] setInteger:newCount forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self.showCountCache setObject:@(newCount) forKey:managerType];
        
        [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] 线程安全更新Facebook展示次数: %ld", managerType, (long)newCount];
    });
}

- (void)incrementFacebookClickCountForManager:(NSString *)managerType {
    dispatch_async(self.facebookCountQueue, ^{
        NSString *key = [self clickCountKeyForManager:managerType];
        NSInteger currentCount = [[NSUserDefaults standardUserDefaults] integerForKey:key];
        NSInteger newCount = currentCount + 1;
        
        [[NSUserDefaults standardUserDefaults] setInteger:newCount forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self.clickCountCache setObject:@(newCount) forKey:managerType];
        
        [IMLogUtils debug:IMLogTagAd format:@"📊 [%@] 线程安全更新Facebook点击次数: %ld", managerType, (long)newCount];
    });
}

- (NSString *)showCountKeyForManager:(NSString *)managerType {
    return [NSString stringWithFormat:@"%@_FB_ShowCount", managerType];
}

- (NSString *)clickCountKeyForManager:(NSString *)managerType {
    return [NSString stringWithFormat:@"%@_FB_ClickCount", managerType];
}

- (NSString *)lastUpdateDateKeyForManager:(NSString *)managerType {
    return [NSString stringWithFormat:@"%@_FB_LastUpdateDate", managerType];
}

- (NSString *)getTodayDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    return [formatter stringFromDate:[NSDate date]];
}

@end